<template>
  <div class="mobile-take-sheet-modify">
    <page-wrapper>
      <div v-loading="loading">
        <!-- 基础信息表单 -->
        <j-border class="form-border">
          <j-form layout="vertical" v-bind="formData">
            <j-form-item label="单据号" :span="24" :contentNest="false">
              <a-input v-model:value="formData.code" disabled style="font-size: 16px;" />
            </j-form-item>
            
            <j-form-item label="关联盘点任务" :span="24" :contentNest="false">
              <a-auto-complete
                v-model:value="searchPlanText"
                :options="planOptions"
                @search="handlePlanSearch"
                @select="handleSelectPlan"
                placeholder="请输入盘点任务号或仓库搜索"
                style="font-size: 16px;"
              />
            </j-form-item>
            
            <j-form-item label="预先盘点单" :span="24" :contentNest="false">
              <a-select
                v-model:value="formData.preSheetId"
                :options="preSheetOptions"
                placeholder="请选择预先盘点单"
                style="font-size: 16px; width: 100%;"
              >
                <template #option="{ label, value }">
                  <div style="display: flex; justify-content: space-between;">
                    <span>{{ label }}</span>
                  </div>
                </template>
              </a-select>
            </j-form-item>
            
            <j-form-item label="仓库" :span="24" :contentNest="false">
              <a-input v-model:value="formData.scName" disabled style="font-size: 16px;" />
            </j-form-item>
            
            <j-form-item label="备注" :span="24" :contentNest="false">
              <a-textarea v-model:value="formData.description" placeholder="请输入备注" />
            </j-form-item>
          </j-form>
        </j-border>

        <!-- 商品列表 -->
        <div class="goods-list-container">
          <div class="goods-list-header">
            <span>商品明细</span>
          </div>
          <div class="goods-toolbar">
            <a-button type="primary" @click="addProduct" class="add-btn">添加商品</a-button>
          </div>
          <vxe-grid
            ref="grid"
            show-overflow
            highlight-hover-row
            row-id="id"
            :data="tableData"
            :columns="tableColumn"
            height="300"
          />
        </div>

        <!-- 底部按钮 -->
        <div class="bottom-buttons">
          <a-button @click="cancel" class="cancel-btn">取消</a-button>
          <a-button type="primary" @click="submit" class="submit-btn">保存</a-button>
        </div>
      </div>
    </page-wrapper>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, computed } from 'vue';
import * as api from '@/api/sc/stock/take/sheet';

const props = {
  id: {
    type: String,
    required: true,
  },
};

export default defineComponent({
  name: 'MobileTakeSheetModify',
  props,
  setup() {
    const state = reactive({
      loading: false,
      searchPlanText: '',
      planOptions: [],
      preSheetOptions: [],
      formData: {
        id: '',
        code: '',
        planId: '',
        planCode: '',
        scName: '',
        preSheetId: '',
        description: '',
        details: [],
      },
      tableData: [],
      tableColumn: [
        {
          field: 'productName',
          title: '商品名称',
          width: 200,
          slots: {
            default: 'productName',
          },
        },
        {
          field: 'stockNum',
          title: '库存',
          width: 70,
        },
        {
          field: 'takeNum',
          title: '盘点数',
          width: 80,
          slots: {
            default: 'takeNum',
          },
        },
        {
          field: 'spec',
          title: '规格',
          width: 80,
        },
        // {
        //   field: 'unit',
        //   title: '单位',
        //   width: 60,
        // },
        {
          title: '操作',
          width: 80,
          fixed: 'right',
          slots: {
            default: 'action',
          },
        },
      ],
    });

    return { ...toRefs(state) };
  },
  created() {
    this.loadFormData();
  },
  methods: {
    // 加载表单数据
    loadFormData() {
      this.loading = true;
      api
        .getDetail(this.id)
        .then((data) => {
          this.formData = data;
          this.searchPlanText = `${data.planCode} (${data.scName})`;
          this.tableData = data.details || [];
          this.loadPreSheetOptions(data.planId);
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 加载预先盘点单选项
    loadPreSheetOptions(planId) {
      api.getPreTakeStockSheets(planId).then((data) => {
        this.preSheetOptions = data.map((item) => ({
          label: item.code,
          value: item.id,
        }));
      });
    },

    // 搜索盘点任务
    handlePlanSearch(value) {
      if (value) {
        api.searchTakeStockPlans({ keyword: value }).then((data) => {
          this.planOptions = data.map((item) => ({
            value: item.id,
            label: `${item.code} (${item.scName})`,
            ...item,
          }));
        });
      }
    },

    // 选择盘点任务
    handleSelectPlan(value, option) {
      this.formData.planId = value;
      this.formData.planCode = option.code;
      this.formData.scName = option.scName;
      this.loadPreSheetOptions(value);
    },

    // 添加商品
    addProduct() {
      this.tableData.push(this.emptyProduct());
    },

    // 创建空商品对象
    emptyProduct() {
      return {
        id: '',
        productId: '',
        productName: '',
        spec: '',
        unit: '',
        stockNum: 0,
        takeNum: 0,
        productCode: '',
      };
    },

    // 搜索商品
    queryProduct(keyword, rowIndex) {
      return api.searchProducts({ keyword }).then((data) => {
        return data.map((item) => ({
          value: item.id,
          label: `${item.code} - ${item.name}`,
          ...item,
        }));
      });
    },

    // 选择商品
    handleSelectProduct(value, option, row) {
      row.productId = value;
      row.productCode = option.code;
      row.productName = option.name;
      row.spec = option.spec;
      row.unit = option.unit;
      // 加载库存数量
      api.getProductStockNum({ productId: value, scId: option.scId }).then((data) => {
        row.stockNum = data.stockNum || 0;
      });
    },

    // 删除商品
    delProduct(index) {
      this.$confirm('确定要删除该商品吗？', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(() => {
        this.tableData.splice(index, 1);
      });
    },

    // 表单验证
    validParams() {
      if (!this.formData.planId) {
        this.$message.error('请选择关联盘点任务');
        return false;
      }

      const invalidRow = this.tableData.find((row) => !row.productId || !row.takeNum);
      if (invalidRow) {
        this.$message.error('请完善商品信息和盘点数量');
        return false;
      }

      return true;
    },

    // 提交表单
    submit() {
      if (!this.validParams()) {
        return;
      }

      this.loading = true;
      const data = {
        ...this.formData,
        details: this.tableData,
      };
      
      api.update(data).then(() => {
        this.$message.success('保存成功');
        this.$router.go(-1);
      }).finally(() => {
        this.loading = false;
      });
    },

    // 取消操作
    cancel() {
      this.$router.go(-1);
    },
  },
});
</script>

<style scoped lang="less">
.mobile-take-sheet-modify {
  padding: 12px;
  font-size: 16px; // 增加基础字体大小

  // 表单相关样式
  .form-border {
    margin-bottom: 15px;
    padding: 10px;
  }

  .ant-form-item-label > label {
    font-size: 16px; // 表单标签字体大小
  }

  // 商品列表样式
  .goods-list-container {
    margin-bottom: 15px;
  }

  .goods-list-header {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 10px;
    padding: 5px 0;
    border-bottom: 1px solid #e8e8e8;
  }

  .goods-toolbar {
    margin-bottom: 10px;
  }

  .add-btn {
    width: 100%;
    font-size: 16px;
    height: 40px;
  }

  // 表格样式调整
  :deep(.vxe-table) {
    font-size: 16px; // 表格字体大小

    .ant-input-number {
      font-size: 16px;
    }
  }

  // 底部按钮样式
  .bottom-buttons {
    display: flex;
    gap: 10px;
    button {
      flex: 1;
      font-size: 18px; // 底部按钮字体大小
      height: 44px;
    }

    .cancel-btn {
      background: #f5f5f5;
      border-color: #d9d9d9;
    }
  }
}
</style>